using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class TestLoadAb : MonoBehaviour
{
    private const string abFileName = "atlas_omnianimation.bundle";
    private const string uri = "atlas_omnianimation.bundle";

    private AssetBundle m_AssetBundle;
    private GameObject m_GameObject;
    private void OnGUI()
    {
        if (IsClickGuildButton("Unload Asset"))
        {
            if (m_GameObject != null)
            {
                Destroy(m_GameObject);
                m_GameObject = null;
            }

            if (m_AssetBundle != null)
            {
                m_AssetBundle.Unload(true);
                m_AssetBundle = null;
            }
        }

        if (IsClickGuildButton("LoadFromFile"))
        {
            var offset = MapFileNameToInt(abFileName);
            Debug.Log($"[TestLoadAb](OnGUI) offset:{offset}");
            m_AssetBundle = AssetBundle.LoadFromFile($"{Application.streamingAssetsPath}/{abFileName}", 0, (ulong)offset);
            var assets = m_AssetBundle.LoadAllAssets();
            m_GameObject = Instantiate(assets[0]) as GameObject;
        }

        if (IsClickGuildButton("LoadByWebRequest"))
        {
            var offset = MapFileNameToInt(abFileName);
            LoadByWebRequest(uri, 0, offset);
        }
        
    }
    
    public static UnityWebRequest GetAssetBundle(string uri, uint crc, uint offset)
    {
        return new UnityWebRequest(uri, "GET", new SGDownloadHandlerWXAssetBundle(uri, crc, offset), null);
    }

    IEnumerator LoadByWebRequest(string uri, uint crc, uint offset)
    {
        UnityWebRequest request = GetAssetBundle(uri, crc, offset);
        yield return request.SendWebRequest();
        if (request.isHttpError)
        {
            Debug.LogError(GetType() + "/ERROR/" + request.error);
        }
        else
        {
            m_AssetBundle = (request.downloadHandler as SGDownloadHandlerWXAssetBundle).assetBundle;
            var assets = m_AssetBundle.LoadAllAssets();
            m_GameObject = Instantiate(assets[0]) as GameObject;
        }
        request.Dispose();
    }

    private bool IsClickGuildButton(string content)
    {
        return GUILayout.Button(content, GUILayout.Width(200), GUILayout.Height(100));
    }

    public static uint MapFileNameToInt(string fileName, int maxLen = 50)
    {
        int hash = fileName.GetHashCode();
        var mappedValue = (uint)Math.Abs(hash % maxLen) + 1;
        return mappedValue;
    }
}
